from fastapi import APIRouter,HTTPException, Query
from ..model.Word import Word
from src.db.index import SessionDep
from sqlmodel import select
from typing import Annotated

router = APIRouter(prefix='/words')
@router.post('/')
async def create_word(word: Word, session: SessionDep):
    session.add(word)
    session.commit()
    session.refresh(word)
    return word

@router.post('/batch_add')
async def batch_add_words(words: list[Word], session: SessionDep):
    session.add_all(words)
    session.commit()
    return

@router.get('/')
async def get_words(
        session: SessionDep, 
        offset: Annotated[int, Query()] = 0, 
        limit: Annotated[int, Query()] = 100
    ):
    query = select(Word).offset(offset).limit(limit)
    words = session.exec(query).all()
    return words

@router.get('/{id}')
async def get_word(id: int, session: SessionDep):
    word = session.get(Word, id)
    if not word:
        return HTTPException(status_code=404, detail='Word not found')
    return word

@router.put('/{id}')
async def update_word(id: int, word: Word, session: SessionDep):
    db_word = session.get(Word, id)
    if not db_word:
        return HTTPException(status_code=404, detail='Word not found')
    word_data = word.model_dump(exclude_unset=True)
    db_word.sqlmodel_update(word_data)
    session.add(db_word)
    session.commit()
    session.refresh(db_word)
    return db_word



